package com.example.ui.share;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.Communication;
import com.example.ui.homepage.HomePageView;
import com.example.util.Util;

public class SelectAlbumActivity extends Activity {
	private Button leftBtn,rightBtn,selectBtn;
	private TextView titleText,selectNumText;
	private GridView gridView;
	
	private List<Map<String, String>> mList = new ArrayList<Map<String, String>>();// 存放当前文件夹中的图片的地址信息
	private List<String> mSelect = new ArrayList<String>();// 存放当前用户选择的图片的编号
	
	private AlbumAdapter mAdapter;
	
	/**
	 * 屏幕的宽度和高度
	 */
	private int mScreenWidth;
	private int mScreenHeight;
	private String headPath;
	
	public static final int  FAIL= 0;
	public static final int  UPLOAD_SUCCESS= 1;
	public static final int DELETE_SUCCESS = 2;
	public static final int ADD_SHARE_SUCCESS = 3;
	public static Handler handler;
	public static List<String> imgList;
	
//	public static StringBuffer sb;
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_album);
		/**
		 * 获取屏幕宽度和高度
		 */
		headPath=HSApplication.sp.getString("imgHead","").toString();
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		mScreenWidth = metric.widthPixels;
		mScreenHeight = metric.heightPixels;
		
		findView();
		gridView();
		
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case FAIL:
					Util.toast(SelectAlbumActivity.this, "网络连接有误");
					break;
				case UPLOAD_SUCCESS:
					Util.toast(SelectAlbumActivity.this, "上传成功");
					break;
				case DELETE_SUCCESS:
					Util.toast(SelectAlbumActivity.this, "删除成功");
					break;
				case ADD_SHARE_SUCCESS:
					Util.toast(SelectAlbumActivity.this, "发表成功");
					break;

				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
	}


	private void findView() {
		leftBtn=(Button)findViewById(R.id.layout_title_left_btn);
		rightBtn=(Button)findViewById(R.id.layout_title_right_btn);
		titleText=(TextView)findViewById(R.id.layout_title_middle_text);
		gridView=(GridView)findViewById(R.id.select_album_gridview);
		selectBtn=(Button)findViewById(R.id.select_album_sure_btn);
		selectNumText=(TextView)findViewById(R.id.select_album_count);
		init();
	}
	
	private void init(){
		leftBtn.setText("返回");
		rightBtn.setText("全选");
		titleText.setText("选择图片");
		
		clickListener();
	}



	private void gridView() {
		// 获取当前文件夹的路径
		String path = getIntent().getStringExtra("path");
		// 根据文件夹的路径获取文件夹里的图片信息
		mList = HSApplication.albumMap.get(path);
		// 更新界面显示数量内容
		initCount(mSelect.size());
		// 初始化适配器
		mAdapter = new AlbumAdapter();
		// 添加适配器
		gridView.setAdapter(mAdapter);
		
		
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// 查看当前点击的条目是否已经选中,选中则移出,没选中则删除
				if (mSelect.contains(String.valueOf(arg2))) {
					mSelect.remove(String.valueOf(arg2));
				} else {
					mSelect.add(String.valueOf(arg2));
				}
				// 如果全部选中则显示反选,否则显示全选
				if (mSelect.size() == mList.size()) {
					rightBtn.setText("反选");
				} else {
					rightBtn.setText("全选");
				}
				// 更新界面显示数量内容
				initCount(mSelect.size());
				// 刷新界面
				mAdapter.notifyDataSetChanged();
			}
		});
	}

	
	private void clickListener() {
		leftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();	
			}
		});
		
		rightBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mSelect.size() == mList.size()) {
					// 全部选中时,点击为反选,所以清空
					mSelect.clear();
				} else if (mSelect.size() > 0) {
					// 当已选中时,点击为全选,添加没选择中的
					for (int i = 0; i < mList.size(); i++) {
						if (mSelect.contains(String.valueOf(i))) {
							continue;
						}
						mSelect.add(String.valueOf(i));
					}
				} else {
					// 没选中,点击为全选,添加所有
					for (int i = 0; i < mList.size(); i++) {
						mSelect.add(String.valueOf(i));
					}
				}
				// 如果全部选中则显示反选,否则显示全选
				if (mSelect.size() == mList.size()) {
					rightBtn.setText("反选");
				} else {
					rightBtn.setText("全选");
				}
				// 更新界面显示数量内容
				initCount(mSelect.size());
				// 刷新界面
				mAdapter.notifyDataSetChanged();
			}
		});
		
		
		selectBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SelectAlbumActivity.this,PublishShareActivity.class);
				String[] imgArr = new String[mSelect.size()];
				for(int i=0;i<mSelect.size();i++){
					 imgArr[i] = mList.get(Integer.parseInt(mSelect.get(i))).get("image_path");
					upload(i);
				}
				intent.putExtra("imgArr", imgArr);
				intent.putExtra("type", "album");
				intent.putExtra("albumImg",mList.get(Integer.parseInt(mSelect.get(0))).get("image_path"));
				intent.putExtra("myHead", headPath);
//				intent.putExtra("sb", HSApplication.sb.toString());
				startActivity(intent);
				finish();
			}

			
		});
		
	}
	private void upload(final int position) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
							try {
								Communication.uploadSharePicture(SelectAlbumActivity.this,mList.get(Integer.parseInt(mSelect.get(position))).get("image_path"));
							} catch (NumberFormatException e) {
								Util.toast(SelectAlbumActivity.this, "图片"+position+"上传失败");
								e.printStackTrace();
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					}
				});
				
			}
		}).start();
	}
	
	/**
	 * 更新界面显示数量内容
	 * 
	 * @param count
	 *            选中的图片数量
	 */
	private void initCount(int count) {
		// 更新选择的图片数量,如果数量大于0,设置确定按钮为可用,反之不可用并修改字体颜色
		if (count > 0) {
			selectNumText.setText("已选择" + count + "张");
			selectNumText.setTextColor(0xFFFFFFFF);
			selectBtn.setTextColor(0xFFFFFFFF);
			selectBtn.setEnabled(true);
			selectBtn.setClickable(true);
		} else {
			selectNumText.setText("已选择0张");
			selectNumText.setTextColor(0xFF999999);
			selectBtn.setTextColor(0xFF999999);
			selectBtn.setEnabled(false);
			selectBtn.setClickable(false);
		}
	}
	
	
	private class AlbumAdapter extends BaseAdapter {

		public int getCount() {
			return mList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(SelectAlbumActivity.this).inflate(
						R.layout.select_album_grid_item, null);
				holder = new ViewHolder();
				holder.photo = (ImageView) convertView
						.findViewById(R.id.album_item_photo);
				holder.select = (ImageView) convertView
						.findViewById(R.id.album_item_select);
				
				// padding大小为40dip,计算px值
				int padding = (int) TypedValue.applyDimension(
						TypedValue.COMPLEX_UNIT_DIP, 40, SelectAlbumActivity.this
								.getResources().getDisplayMetrics());
				// 设置显示的图片大小为屏幕宽度1/4大小
				LayoutParams params = new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				params.width = (mScreenWidth - padding) / 4;
				params.height = (mScreenWidth - padding) / 4;
				holder.photo.setLayoutParams(params);
//				holder.select.setLayoutParams(params);
				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// 添加图片
			holder.photo.setImageBitmap(Util.getImageThumbnail(mList.get(position).get("image_path"), 70, 70));
			
			// 查看是否选中,选中则显示选中效果
			if (mSelect.contains(String.valueOf(position))) {
				holder.select.setVisibility(View.VISIBLE);
			} else {
				holder.select.setVisibility(View.GONE);
			}
			return convertView;
		}

		class ViewHolder {
			ImageView photo;
			ImageView select;
		}
	}
	
	

}
